import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/home/home.vue'
import store from '../store/store'
import {getUserInfo} from '../api/login'
Vue.use(Router)
// 路由添加方法：当路由没有子页面，需要设置一个子路由指向路由自己。
//             如果有子页面，正常添加子路由。

const constantRouterMap = [
  {
    path: '/404',
    name: 'HTTP404',
    component: () => import('../views/404/index.vue'),
    hidden: true
  },
  {
    path: '/login',
    name: 'Login',
    // 懒加载方式，当路由被访问的时候才加载对应组件
    component: () => import('../views/login/login.vue'),
    hidden: true
  },
  {
    path: '/',
    component: Home,
    name: '首页',
    redirect: '/dashboard',
    hidden: true,
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index.vue')
      }
    ]
  },
  {
    path: '/business',
    component: Home,
    children: [
      {
        path: 'index',
        name: '业务管理',
        component: () => import('../views/business/index.vue'),
        meta: {title: '业务管理', icon: true}
      }
    ]
  },
  {
    path: '/finance',
    component: Home,
    children: [
      {
        path: 'index',
        name: '财务管理',
        meta: {title: '财务管理', icon: true},
        component: () => import('../views/finance/index.vue')
      }
    ]
  },
  {
    path: '/operations',
    component: Home,
    name: '运营管理',
    meta: {title: '运营管理', icon: true, permissions: ['运营管理', '产品数据', '推广数据']},
    children: [
      {
        path: 'prodata',
        name: '产品数据',
        meta: {title: '产品数据', permissions: ['运营管理', '产品数据']},
        component: () => import('../views/operations/prodata/index.vue')
      },
      {
        path: 'promotiondata',
        name: '推广数据',
        meta: {title: '推广数据', permissions: ['运营管理', '推广数据']},
        component: () => import('../views/operations/promotiondata/index.vue')
      }
    ]
  },
  {
    path: '/system',
    name: '系统管理',
    component: Home,
    redirect: '/system/user',
    meta: {title: '系统管理', icon: true, permissions: ['系统管理', '人员管理', '角色管理']},
    children: [
      {
        path: 'user',
        name: '人员管理',
        meta: {title: '人员管理', permissions: ['系统管理', '人员管理']},
        component: () => import('../views/user/index.vue'),
        children: [
          {
            path: 'adduser',
            name: 'AddUser',
            hiddern: true,
            component: () => import('../views/user/adduser/index.vue'),
            meta: {title: '添加'}
          },
          {
            path: 'edituser',
            name: 'EditUser',
            hiddern: true,
            component: () => import('../views/user/edituser/index.vue'),
            meta: {title: '编辑'}
          },
          {
            path: 'usermanagement',
            name: 'UserManagement',
            component: () => import('../views/user/usermanagement/index.vue'),
            meta: {title: '管理'}
          }
        ]
      },
      {
        path: 'role',
        name: '角色管理',
        component: () => import('../views/role/index.vue'),
        meta: {title: '角色管理', permissions: ['系统管理', '角色管理']},
        children: [
          {
            path: 'addrole',
            name: 'AddRole',
            component: () => import('../views/role/addrole/index.vue'),
            meta: {title: '添加'}
          },
          {
            path: 'editrole',
            name: 'EditRole',
            component: () => import('../views/role/editrole/index.vue'),
            meta: {title: '编辑'}
          },
          {
            path: 'rolemanagement',
            name: 'RoleManagement',
            component: () => import('../views/role/rolemanagement/index.vue'),
            meta: {title: '管理'}
          }
        ]
      }
    ]
  },
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]
const asyncRouterMap = [
]
const router = new Router({
  routes: constantRouterMap
})
router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    let token = window.sessionStorage.getItem('token')
    if (!store.state.asyncRouterLoad) {
      store.commit('CLEAR_SHOWROUTERMAP')
      store.commit('SET_SHOWROUTERMAP', constantRouterMap)
    }
    if (!token) {
      next('/login')
    } else {
      getUserInfo(token).then(res => {
        let {code, userInfo} = res.data
        if (code === 200) {
          store.commit('SET_USERNAME', userInfo.username)
          store.commit('SET_UID', userInfo.uid)
          store.commit('CLEAR_ROLE')
          store.commit('SET_ROLE', userInfo.role)
          const accessedRouterMap = filterAsyncRouter(asyncRouterMap, userInfo.role.permissions)
          if (!store.state.asyncRouterLoad) {
            store.commit('SET_SHOWROUTERMAP', accessedRouterMap)
            store.commit('SET_ASYNCROUTERLOAD', !store.state.asyncRouterLoad)
            router.addRoutes(accessedRouterMap)
          }
          next()
        }
      }).catch(err => {
        console.log(err)
        next({path: '/login'})
      })
    }
  } else {
    window.sessionStorage.removeItem('token')
    next()
  }
})
export default router
function hasPermission (permissions, route) {
  if (route.meta && route.meta.permissions) {
    return permissions.some(permission => {
      return route.meta.permissions.indexOf(permission) >= 0
    })
  } else {
    return true
  }
}
//
function filterAsyncRouter (asyncRouterMap, permissions) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(permissions, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, permissions)
      }
      return true
    }
    return false
  })
  return accessedRouters
}
